package com.bjb.vr.auth.filter;

import com.bjb.vr.auth.util.AccessRequestUtil;
import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.result.BaseErrorCode;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @description:
 * @author: HuJingBo
 * @time: 2022/5/18 13:06
 */
@Slf4j
public class CustomHeaderAuthencationFilter extends BasicAuthenticationFilter {

    public CustomHeaderAuthencationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 检查请求头中Token是否合法
        Map<String, String> headers = AccessRequestUtil.takeHeaders();
        if (!headers.containsKey(TokenConstants.AUTHORIZATION.toLowerCase()) || StringUtils.isBlank(headers.get(TokenConstants.AUTHORIZATION.toLowerCase()))) {
            String errMsg = BaseErrorCode.UNAUTHORIZED.getMessage();
            log.error(errMsg + " 请求路径：{}", request.getRequestURI());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.Fail(errMsg)));
            return;
        }

        CommonResult commonResult = JwtTokenUtil.validateJWT(headers.get(TokenConstants.AUTHORIZATION.toLowerCase()));
        if (!commonResult.isSuccess()) {
            String errMsg = commonResult.getMessage();
            log.error(errMsg + " 请求路径：{}", request.getRequestURI());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.Fail(errMsg)));
            return;
        }

        // 校验通过放行
        chain.doFilter(request,response);
    }
}
